import hashlib

from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from app.models.login import Login

# cookie加密常量
salts = '3l)ux*85ba(epdi%mvtqi8o1a3mn(=38@##rfp3voqwtyf'


def take_md5(content):
	hash = hashlib.md5()  # 创建hash加密实例
	hash.update(content.encode("utf8"))  # hash加密
	result = hash.hexdigest()  # 得到加密结果
	return result


# 登录页
def login_index(request):
	if 'cookie_customCheck' in request.COOKIES:
		# 获取记住的用户名
		username = request.get_signed_cookie('cookie_username', salt=salts)
		password = request.get_signed_cookie('cookie_password', salt=salts)
		customCheck = request.get_signed_cookie('cookie_customCheck', salt=salts)
	else:
		username = ''
		password = ''
	return render(request, 'visites/login.html', locals())


# 登录操作
def login_check(request):
	if request.method == 'POST':
		username = request.POST['username']
		password = request.POST['password']
		customCheck = request.POST['customCheck']
		suser = Login.objects.filter(name=username)
		if suser:
			for a in suser:
				password = take_md5(password)
				if a.pwd == password:
					request.session['session_name'] = username
					request.session['session_password'] = password
					# 判断是否要记住用户名的状态,1是选中，0是未选中
					if customCheck == '1':
						# 将username,password,customCheck写入浏览器cookie,失效时间为18000
						res = HttpResponse('1')
						password = request.POST['password']
						res.set_signed_cookie('cookie_username', username, salt=salts, max_age=18000)
						res.set_signed_cookie('cookie_password', password, salt=salts, max_age=18000)
						res.set_signed_cookie('cookie_customCheck', customCheck, salt=salts, max_age=18000)
						return res
					else:
						res = HttpResponse('1')
						return res
				elif password == '':
					return HttpResponse('2')
				else:
					return HttpResponse('-1')
		elif username == '' or password == '':
			return HttpResponse('2')
		else:
			return HttpResponse('-1')
	else:
		return HttpResponse('0')


# # 登录成功跳转的页面（首页）
# def index(request):
# 	sessionName = request.session.get('session_name', None)
# 	return render(request, 'visites/temp-index.html', {'sessionName': sessionName})


# 退出登录
def logout(request):
	# 删除username 的 session
	del request.session['session_name']
	return HttpResponseRedirect('/')
